{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "acbd8dee-75ad-4ccc-b70b-dd2210394320",
   "metadata": {},
   "source": [
    "# Direct Prompting on CSQA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b96e3d1a-568e-435e-b7b9-15eb334df5e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import time\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "from tqdm import tqdm\n",
    "from pprint import pprint\n",
    "from tenacity import retry, stop_after_attempt, wait_chain, wait_fixed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "344f7f75-3be7-4609-aeef-1b52c4da9a21",
   "metadata": {},
   "outputs": [],
   "source": [
    "@retry(wait=wait_chain(*[wait_fixed(3) for i in range(3)] +\n",
    "                       [wait_fixed(5) for i in range(2)] +\n",
    "                       [wait_fixed(10)]))\n",
    "def completion_with_backoff(**kwargs):\n",
    "    return openai.Completion.create(**kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a310ade8-8e52-4f09-baf3-0a0b5c13deb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "openai.api_key = \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9f466685-c523-462d-8e55-b30ba41afae8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_jsonl(path):\n",
    "    data=[]\n",
    "    with open(path, 'r', encoding='utf-8') as reader:\n",
    "        for line in reader:\n",
    "            data.append(json.loads(line))\n",
    "    return data "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "95a24d47-d389-44b7-933c-6df12f5ed21b",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = load_jsonl('data/train_rand_split.jsonl')\n",
    "dev_data = load_jsonl('data/dev_rand_split.jsonl')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43a28a06-4d9d-45bf-aef7-c0676d6cb960",
   "metadata": {},
   "source": [
    "# Original Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c4e8422b-eb26-4cd4-bf0c-bfba0da1ae5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_original_direct = open('lib_prompt/prompt_original_direct.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2cbaff8e-9362-41b4-a6fc-1bef9271ec80",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1221/1221 [13:23<00:00,  1.52it/s]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_gpt3_original_direct.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']['stem']\n",
    "        a = d['answerKey'].lower()\n",
    "        \n",
    "        prompt_q = prompt_original_direct + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'Answer Choices:\\n'\n",
    "        for c in d['question']['choices']:\n",
    "            prompt_q += '(%c) %s\\n' % (c['label'].lower(), c['text'])\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"text-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('(')\n",
    "        if(len(ans_) > 1): ans_ = ans_[1][0]\n",
    "        else: ans_ = 'a'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "31fd6308-ce43-4ef8-988f-3b52eb2e89db",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 1221 correct 967 acc 0.7920\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a16973f2-4cba-4d3e-b8f3-660a0d68bfd5",
   "metadata": {},
   "source": [
    "# Complex Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "56becf73-47a7-4e9b-a5f3-6981b3c75155",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_complex_direct = open('lib_prompt/prompt_complex_direct.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "b7f70faa-f34b-40a1-af67-0f28480f4712",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1221/1221 [13:51<00:00,  1.47it/s]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_gpt3_complex_direct.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']['stem']\n",
    "        a = d['answerKey'].lower()\n",
    "        \n",
    "        prompt_q = prompt_complex_direct + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'Answer Choices:\\n'\n",
    "        for c in d['question']['choices']:\n",
    "            prompt_q += '(%c) %s\\n' % (c['label'].lower(), c['text'])\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"text-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('(')\n",
    "        if(len(ans_) > 1): ans_ = ans_[1][0]\n",
    "        else: ans_ = 'a'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "b907a9ab-9c89-4620-bf37-495ea023aa7a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 1221 correct 944 acc 0.7731\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a824b6ab-504a-4a96-9da2-4f2124cf691c",
   "metadata": {},
   "source": [
    "# Simple Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "10ea0fda-c0f5-467c-b2cd-25a0b131af31",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_simple_direct = open('lib_prompt/prompt_simple_direct.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "bcc912e1-7757-418f-bcf2-5c6abe1881e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1221/1221 [13:00<00:00,  1.56it/s]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_gpt3_simple_direct.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']['stem']\n",
    "        a = d['answerKey'].lower()\n",
    "        \n",
    "        prompt_q = prompt_simple_direct + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'Answer Choices:\\n'\n",
    "        for c in d['question']['choices']:\n",
    "            prompt_q += '(%c) %s\\n' % (c['label'].lower(), c['text'])\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"text-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('(')\n",
    "        if(len(ans_) > 1): ans_ = ans_[1][0]\n",
    "        else: ans_ = 'a'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "3f3f3f65-543b-474c-9e71-baef709182b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 1221 correct 959 acc 0.7854\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
